<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\TeamCashApply;
use App\Models\TeamCashInfo;
use App\Models\UserProjectOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class TeamCashApplyController extends Controller
{

    public function cashProject(Request $request)
    {
        $user = $request->user();

        if($user->type != 2)
        {
            throw new \Exception('权限不足');
        }

        $cashInfo = TeamCashInfo::where('team_id', $user->team_id)->first();


        $node = Project::where('team_id', $user->team_id)->selectRaw("GROUP_CONCAT(id) as ids")->first();

        $node = UserProjectOrder::whereIn('project_id', explode(",", $node->ids));

        $node = $node->selectRaw("project_id, sum(case when status = 1 then amount else 0  end) as settled,sum(case when status = 0 then amount else 0  end) as unsettled, count(case when status = 0 then 1  end) as unsettled_count");
        $node = $node->groupBy('project_id')->havingRaw("count(case when status = 0 then 1 end) > 0");

        $list = $node->get();

        $rs = [];
        $total = [
            'settled' => 0.0,
            'unsettled_count' => 0,
            'unsettled' => 0.0,
        ];
//        dd($list->toArray(), gettype($list));
        foreach($list as $value)
        {
            $value = $value->toArray();

            $value['project_info'] = Project::findorFail($value['project_id']);

            $rs[] = $value;
            $total['settled'] += $value['settled'];
            $total['unsettled_count'] += $value['unsettled_count'];
            $total['unsettled'] += $value['unsettled'];
        }

        return $this->returnJSON([
            'total' => $total,
            'rows' => $rs,
            'cashInfo' => $cashInfo,
        ]);
    }

    public function apply(Request $request)
    {
        $user = $request->user();

        if($user->type != 2)
        {
            throw new \Exception('权限不足');
        }
        $pids = $request->get('ids');

        $node = Project::where('team_id', $user->team_id)->selectRaw("GROUP_CONCAT(id) as ids")->first();

        $node = UserProjectOrder::whereIn('project_id', explode(",", $node->ids))->whereIn('project_id', explode(',', $pids));

        $node = $node->selectRaw("project_id, sum(case when status = 1 then amount else 0  end) as settled,sum(case when status = 0 then amount else 0  end) as unsettled, count(case when status = 0 then 1  end) as unsettled_count");
        $node = $node->groupBy('project_id')->havingRaw("count(case when status = 0 then 1 end) > 0");

        $list = $node->get();

        $rs = $total = [];
        foreach($list as $value)
        {
            $value = $value->toArray();

            $value['project_info'] = Project::findorFail($value['project_id']);

            $rs[] = $value;

            $total['settled'] += $value['settled'];
            $total['unsettled_count'] += $value['unsettled_count'];
            $total['unsettled'] += $value['unsettled'];
        }

        $cashInfo = TeamCashInfo::where('team_id', $user->team_id)->first();

        return $this->returnJSON([
            'total' => $total,
            'rows' => $rs,
            'cashInfo' => $cashInfo,

        ]);
    }

    public function index(Request $request) {
        $user = $request->user();
        $node = TeamCashApply::with(['org', 'team']);
        $perPage = $request->get('perPage', 10);

        if($user->type == 3)
        {
            $node->where('org_id', $user->org_id);
        }elseif($user->type == 4)
        {

        }else{
            throw new \Exception('权限不足');
        }


//        $node->where('verify_status', 0);

        $node->orderBy('id', 'desc');

        $info = $node->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);

    }

    public function verify(Request $request, $id)
    {
        $cashApply = TeamCashApply::findorfail($id);

        $user = $request->user();

        if($user->type == 3)
        {
            if($cashApply->org_id != $user->org_id)
            {
                return $this->returnJSON(null, 0, '权限错误');
            }
        }elseif($user->type == 4)
        {

        }else{
            throw new \Exception('权限不足');
        }

        $this->validate($request, [
//            'verify_status' => 'required|in:0,1,2',
            'verify_msg' => 'max:255',
        ]);

        $data = $request->only(['verify_status', 'verify_msg']);
        if ($request->has('verify_status')){
            $data['verify_status'] = $request->get('verify_status');
        }

        $cashApply->fill($data);
        if($cashApply->save())
        {
            if($cashApply->verify_status == 2)
            {
                DB::table('user_project_order')->where('cash_apply_id', $cashApply->id)->update(['status'=>0, ]);
            }elseif($cashApply->verify_status == 1)
            {
                DB::table('user_project_order')->where('cash_apply_id', $cashApply->id)->update(['status'=>1, ]);
            }
            return $this->returnJSON(null, 0, '修改成功');
        }
        return $this->returnJSON(null, 500, '修改失败');
    }

    public function show(Request $request, $id) {

        $cashApply = TeamCashApply::findorfail($id);

        $user = $request->user();

        if($user->type == 2)
        {
            if($cashApply->team_id != $user->team_id)
            {
                return $this->returnJSON(null, 0, '权限错误');
            }
        }elseif($user->type == 3)
        {
            if($cashApply->org_id != $user->org_id)
            {
                return $this->returnJSON(null, 0, '权限错误');
            }
        }elseif($user->type == 4)
        {

        }else{
            throw new \Exception('权限不足');
        }


        return $this->returnJSON($cashApply->toArray(), 0, 'ok');
    }

    public function store(Request $request) {

        $user = $request->user();

        if($user->type != 2)
        {
            throw new \Exception('权限不足');
        }
        $pids = $request->get('ids');

        $node = Project::where('team_id', $user->team_id)->selectRaw("GROUP_CONCAT(id) as ids")->first();

        $node = UserProjectOrder::whereIn('project_id', explode(",", $node->ids))->whereIn('project_id', explode(',', $pids));

        $node = $node->where('status', 0);

        $list = $node->get();

        if(count($list) == 0)
        {
            return $this->returnJSON(null, 500, '非法项目id');
        }

        $cashInfo = TeamCashInfo::where('team_id', $user->team_id)->first();
        if(empty($cashInfo) || $cashInfo->verify_status != 1)
        {
            return $this->returnJSON(null, 500, '团队提现信息错误');
        }
        $rs = $total = [];
        $amount = 0;
        foreach($list as $value)
        {
            $ordIds[] = $value->id;
            $amount += $value->amount;
        }

        $cashApply = new TeamCashApply();

        $data['team_id'] = $user->team_id;
        $data['org_id'] = $user->org_id;
        $data['order_count'] = count($ordIds);
        $data['amount'] = $amount;
        $data['recive_info'] = $cashInfo->toArray();
        $data['apply_msg'] = $request->input('apply_msg', '');


        $cashApply->fill($data);

        DB::beginTransaction();
        try{
            $cashApply->save();

            DB::table('user_project_order')->whereIn('id', $ordIds)->update(['status'=>3, 'cash_apply_id'=>$cashApply->id, 'cash_time'=>date('Y-m-d H:i:s')]);
            DB::commit();
            return $this->returnJSON(null, 0, '新增成功');
        }catch (\Exception $e)
        {
            Log::info($e->getMessage());
            DB::rollBack();
            return $this->returnJSON(null, 500, '新建失败 '.$e->getMessage());
        }


    }

    public function update(Request $request, $id)
    {
        $cashApply = TeamCashApply::findorfail($id);

        $user = $request->user();

        if($user->type == 3)
        {
            if($cashApply->org_id != $user->org_id)
            {
                return $this->returnJSON(null, 0, '权限错误');
            }
        }elseif($user->type == 4)
        {

        }else{
            throw new \Exception('权限不足');
        }

        $this->validate($request, [
            'apply_msg' => 'max:255',
//            'verify_status' => 'int:0,1,2',
        ]);

        $data = $request->only(['apply_msg']);

        $cashApply->fill($data);
        if($cashApply->save())
        {
            return $this->returnJSON(null, 0, '修改成功');
        }
        return $this->returnJSON(null, 500, '修改失败');

    }

    public function cashHistory(Request $request)
    {
        $user = $request->user();

        if($user->type != 2)
        {
            throw new \Exception('权限不足');
        }

        $node = TeamCashApply::where('team_id', $user->team_id)->selectRaw("* , (amount - service_fee - transfer_fee) as apply_amount");

        if($request->get('verify_status'))
        {
            $node->where('verify_status', $this->get('verify_status'));
        }

        $perPage = $request->get('perPage', 10);

        $node->orderBy('id', 'desc');

        $info = $node->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }



}
